package com.xh.bussiness.xkw.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.xh.bussiness.xkw.constant.XkwAPIURL;
import com.xh.bussiness.xkw.dao.XkwPaperTypeMapper;
import com.xh.bussiness.xkw.model.XkwPaperType;
import com.xh.bussiness.xkw.model.XkwSubject;
import com.xh.bussiness.xkw.service.IXkwPaperTypeService;
import com.xh.bussiness.xkw.service.IXkwSubjectService;
import com.xh.bussiness.xkw.utils.ConfigUtils;
import com.xh.bussiness.xkw.utils.XkwHttpsUtils;
import com.xh.core.service.impl.BaseServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class XkwPaperTypeServiceImpl extends BaseServiceImpl<XkwPaperTypeMapper, XkwPaperType> implements IXkwPaperTypeService {


    private final String XkwApiSeriveUrl;

    @Autowired
    public XkwPaperTypeServiceImpl(ConfigUtils configUtils) {
        XkwApiSeriveUrl = configUtils.getXkwApiSeriveUrl();
    }

    @Autowired
    private IXkwSubjectService xkwSubjectService;
    /**
     * 同步学科网试卷类型
     * @throws Exception
     */
    public void  sysXkwPaperType() throws Exception {
        //查询科目
        List<XkwSubject> subjectList = xkwSubjectService.queryAll();
        for (XkwSubject subject : subjectList) {
            Integer subjectId = subject.getXkwId();
            List<XkwPaperType> quesTypeList = queryPaperTypeBySubjectId(subjectId);
            this.batchInsert(quesTypeList);
        }
    }
    /**
     *  查询学科网试卷类型
     *  @param xkwSubjectId  学科网科目ID
     *
     */
    private  List<XkwPaperType> queryPaperTypeBySubjectId(Integer xkwSubjectId) {
        List<XkwPaperType> paperTypeList = new ArrayList<>();
        String queryUrl = String.format(XkwAPIURL.QUERY_BANKS_PAPER_TYPES, xkwSubjectId);
        String url = XkwApiSeriveUrl + queryUrl;
        String quesTypeJson = XkwHttpsUtils.doGet(url);
        if(null != quesTypeJson){
            List<Map> parse = (List<Map>) JSONArray.parse(quesTypeJson);
            if(!parse.isEmpty()){
                parse.forEach(map -> {
                    Integer id = Integer.valueOf(map.get("id").toString());
                    String name = map.get("name").toString();
                    XkwPaperType xkwPaperType = new XkwPaperType(id,name);
                    paperTypeList.add(xkwPaperType);
                });
            }
        }
        return paperTypeList;
    }

}
